﻿using Adnc.Application.Shared.Services;
using Adnc.Infra.Helper;
using Adnc.Infra.IRepositories;
using Adnc.Infra.Mapper;
using Adnc.Shared.Consts;
using Adnc.Shared.RpcServices.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using WYT.Ord.Application.Contracts.Dtos.ShopCart;
using WYT.Ord.Application.Contracts.Services;
using WYT.Ord.Repository.Entities;

namespace WYT.Ord.Application.Services
{
    /// <summary>
    /// 购入车服务
    /// </summary>
    public class ShoppingCartAppService : AbstractAppService,IShoppingCartAppService
    {
        private readonly IEfRepository<ShoppingCart> _shoppingcartRepository;

        private readonly IUserRpcService _userRpcService;

        private readonly IProductRPCService _productRPCService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="shoppingcartRepository"></param>
        /// <param name="productRPCService"></param>
        /// <param name="userRpcService"></param>
        public ShoppingCartAppService(
            IEfRepository<ShoppingCart> shoppingcartRepository,
            IProductRPCService productRPCService,
            IUserRpcService userRpcService
            )
        {
            _shoppingcartRepository = shoppingcartRepository;
            _productRPCService  = productRPCService;
            _userRpcService = userRpcService;
        }

        /// <summary>
        /// 添加商品进购入车
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<AppSrvResult> AddProduct(long UserId,ProductAddDto input)
        {
            var recode = await _shoppingcartRepository.FindAsync(c => c.UserId.Equals(UserId) && c.GoodsId.Equals(input.GoodsId) && c.SizeId.Equals(input.SizeId));
            if (recode == null)
                await _shoppingcartRepository.InsertAsync(new ShoppingCart()
                {
                    Id = IdGenerater.GetNextId(),
                    UserId = UserId,
                    GoodsId = input.GoodsId,
                    SizeId = input.SizeId,
                    Count = input.Count
                });
            else
            {
                recode.Count += input.Count;
                if(recode.Count < 1)
                    recode.Count = 1;
                await _shoppingcartRepository.UpdateAsync(recode, UpdatingProps<ShoppingCart>(c => c.Count));
            }
            return AppSrvResult();
        }

        /// <summary>
        /// 删除购物
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="Ids"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<AppSrvResult> DeleteProduct(long UserId, long[] Ids)
        {
            await _shoppingcartRepository.DeleteRangeAsync(c => c.UserId.Equals(UserId) && Ids.Contains(c.Id));
            return AppSrvResult();
        }

        /// <summary>
        /// 修改购物车中的商品信息
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<AppSrvResult> UpdateProduct(long UserId, ProductModifyDto input)
        {
            var pro = await _shoppingcartRepository.FindAsync(input.Id);
            if(pro == null)
                return Problem(HttpStatusCode.NotFound);
            if(pro.UserId != UserId)
                return Problem(HttpStatusCode.BadRequest,"没有权限");

            if (input.SizeId == pro.SizeId)
                return AppSrvResult();

            var isHave = await _shoppingcartRepository.AnyAsync(c => c.UserId == UserId && c.SizeId == input.SizeId);
            if (isHave)
                await _shoppingcartRepository.DeleteAsync(pro.Id);
            else
            {
                pro.SizeId = input.SizeId;
                await _shoppingcartRepository.UpdateAsync(pro, UpdatingProps<ShoppingCart>(c => c.SizeId));
            }

            return AppSrvResult();
        }

        /// <summary>
        /// 获取用户购物车列表
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="language"></param>
        /// <returns></returns>
        public async Task<AppSrvResult<List<ProductListDto>>> GetProductList(long UserId,string language)
        {
            bool isZh = language.Equals(LanguageConsts.ZH);

            //获取用户等级
            var userGradeResponse = await _userRpcService.GetUserGrade();
            if (!userGradeResponse.IsSuccessStatusCode)
                return Problem(HttpStatusCode.InternalServerError, "服务器异常");
            var grade = userGradeResponse.Content;

            List<ProductListDto> result = new List<ProductListDto>();
            var products = await _shoppingcartRepository.Where(c => c.UserId == UserId).ToListAsync();
            if(products.Count == 0)
                return result;

            var sizeIds = products.Select(c => c.SizeId).ToArray();
            var proinfor = await _productRPCService.GetProductSizeDetailByIds(sizeIds,true);

            if (!proinfor.IsSuccessStatusCode)
                return Problem(HttpStatusCode.BadRequest, "系统错误");

            //没有查到商品信息，说明商品已经下架，需要删除掉购物车信息
            if (proinfor.Content == null || proinfor.Content.Count == 0)
            {
                await _shoppingcartRepository.DeleteRangeAsync(c => c.UserId == UserId);
                return result;
            }

            List<long> invalid = new List<long>();
            foreach (var item in products)
            {
                var infor = proinfor.Content.FirstOrDefault(c => c.SizeId == item.SizeId);
                if (infor == null)
                {
                    invalid.Add(item.Id);
                    continue;
                }

                result.Add(new ProductListDto
                {
                    Id = item.Id,
                    GoodsId = infor.GoodsId,
                    GoodsName = isZh ? infor.GoodsName : infor.UighurGoodsName,
                    SizeId = infor.SizeId,
                    SizeName = isZh ? infor.SizeName : infor.UighurSizeName,
                    Count = item.Count,
                    IsForeign = infor.IsForeign,
                    OriginalPrice = infor.Price,
                    Price = infor.ProductPrices.First(c => c.UserLevel == grade).Price,
                    IsThirdParties = infor.IsThirdParties,
                    Thumbnail = infor.Thumbnail,
                    Gifts = infor.Gift.Select(x => new ProductGiftDto() {
                        Id =  x.Id,
                        BuyCount = x.BuyCount,
                        Count = x.Count,
                        GoodsId = x.GoodsId,
                        GoodsName = isZh ? x.GiftDetail.GoodsName : x.GiftDetail.UighurGoodsName,
                        IsSuperposition = x.IsSuperposition,
                        RemainderCount = x.RemainderCount,
                        SizeId = x.SizeId,
                        SizeName= isZh ? x.GiftDetail.SizeName : x.GiftDetail.UighurSizeName,
                        }).ToList()
                });
            }

            return result;
        }
    }
}
